#!/usr/bin/ruby
#Pour installer la bibliothèque grackle : 
#sudo gem sources -a http://gems.github.com ; sudo gem install hayesdavis-grackle
require 'rubygems'
require 'grackle'
require "lib/tree.rb"


class CadavreExquis < TreeNode
  attr_accessor :phrase, :twitt, :childs_computer

  def initialize(twitter, debut)
    raise "Cadavre non initialisé" if debut.nil?
    @phrase = debut.scan(/\w+/)[-3..-1].join(' ')
    @twitter = twitter
    @childs_computer = lambda do |node|
      childs = Array.new
      begin
        query = @twitter[:search].search? :q => '"'+node.phrase+'"'
        puts "Searching \"" + node.phrase + "\""
      rescue Grackle::TwitterError
        puts "Erreur sur la phrase '"+node.phrase+"'"
        raise
      end
      query.results.each do |res|
        suite = res.text
        if suite.upcase.rindex(node.phrase.upcase)
          endphrase = suite[suite.upcase.rindex(node.phrase.upcase) + node.phrase.size, 200]
        end
        mots = Array.new
        mots = endphrase.scan(/\w+/) unless endphrase.nil?
        if mots.size > 2
          child = CadavreExquis.new(@twitter, suite)
          child.twitt = res
          childs << child
        end
      end
      return childs
    end

    super()
  end

  def to_s
    return @phrase
  end

#  def findcourse(func, depth)
#    super(func, depth, @childs_computer)
#  end
end

def clean(str)
  str = str.gsub(/[^a-z\s]/i, '').strip
  return str
end

is_plain_sentence = lambda do |node|
#  print "testing " + node.phrase
  phrase = clean(node.phrase)
  is_plain = (not (phrase.nil? or phrase.empty?))
#  print "..."
#  if is_plain
#    puts "ok"
#  else 
#    puts "nok"
#  end
  return is_plain
end



twitter = Grackle::Client.new
debut = ARGV[0]
depth = ARGV[1] ? ARGV[1].to_i : 4
cadavre = CadavreExquis.new(twitter, debut)
twits = cadavre.findcourse(is_plain_sentence, depth, cadavre.childs_computer)
twits.each { |twit| puts twit.twitt.text + "   [" + twit.twitt.from_user + "]" unless twit.twitt.nil?}

